<script setup>
import List from '../components/List.vue';
import ClusterNamespaceSelector from '../components/ClusterNamespaceSelector.vue'
import { getPodListHandler as getListHandler, deletePodHandler as deleteHandler ,deletePodListHandler } from '../../api/pod.js';
import {reactive, computed, ref, toRefs, onMounted, nextTick} from 'vue'
import { ElMessage,ElMessageBox  } from 'element-plus'
import CodeMirror  from '../components/CodeMirror.vue'
import { obj2Yaml } from '../../utils/utils';
//导入xterm的样式
import { Terminal } from 'xterm';
import {FitAddon} from 'xterm-addon-fit'
import {AttachAddon} from 'xterm-addon-attach'
import 'xterm/css/xterm.css'; // 导入xterm样式，确保终端显示正常

const data = reactive({
  items: [],
  clusterId: "",
  namespace: "",
  yamlContent: "",
  deleteList:[],
  options: {
    selectionList: [],
    selectionSelected: "",
    selectionOptions: [
      {
        label: "删除",
        value: "Delete",
      },
      {
        label: "强制删除",
        value: "ForceDelete",
      },
    ],
  },
  // 🚀 全新炫酷终端配置
  termOptions: {
    rendererType: 'canvas',
    rows: 25,
    cols: 120,
    convertEol: true,
    cursorBlink: true,
    cursorStyle: 'block',
    cursorWidth: 1,
    bellStyle: 'none',
    fontFamily: '"Fira Code", "JetBrains Mono", "Cascadia Code", "SF Mono", Monaco, "Inconsolata", "Liberation Mono", "Menlo", monospace',
    fontSize: 14,
    fontWeight: 'normal',
    letterSpacing: 0,
    lineHeight: 1.2,
    drawBoldTextInBrightColors: true,
    fastScrollModifier: 'alt',
    fastScrollSensitivity: 5,
    macOptionIsMeta: false,
    macOptionClickForcesSelection: false,
    minimumContrastRatio: 1,
    scrollback: 1000,
    scrollSensitivity: 1,
    tabStopWidth: 8,
    // 🎨 赛博朋克风格主题
    theme: {
      // 主要颜色
      foreground: '#00ff88',        // 主前景色 - 霓虹绿
      background: '#0a0a0a',        // 背景色 - 深黑
      cursor: '#ff0080',            // 光标 - 霓虹粉
      cursorAccent: '#00ff88',      // 光标强调色
      
      // 选择相关
      selection: 'rgba(255, 0, 128, 0.3)',
      selectionForeground: '#ffffff',
      
      // 基础16色调色板
      black: '#000000',
      red: '#ff0040',               // 霓虹红
      green: '#00ff88',             // 霓虹绿
      yellow: '#ffff00',            // 霓虹黄
      blue: '#0080ff',              // 霓虹蓝
      magenta: '#ff0080',           // 霓虹粉
      cyan: '#00ffff',              // 霓虹青
      white: '#ffffff',
      
      // 明亮版本
      brightBlack: '#404040',
      brightRed: '#ff4080',
      brightGreen: '#40ff88',
      brightYellow: '#ffff40',
      brightBlue: '#4080ff',
      brightMagenta: '#ff40c0',
      brightCyan: '#40ffff',
      brightWhite: '#ffffff',
      
      // 扩展色彩
      extendedAnsi: [
        '#000000', '#800000', '#008000', '#808000',
        '#000080', '#800080', '#008080', '#c0c0c0',
        '#808080', '#ff0000', '#00ff00', '#ffff00',
        '#0000ff', '#ff00ff', '#00ffff', '#ffffff'
      ]
    }
  },
  // 🎭 主题切换选项
  terminalThemes: {
    cyberpunk: {
      name: '赛博朋克',
      theme: {
        foreground: '#00ff88',
        background: '#0a0a0a',
        cursor: '#ff0080',
        cursorAccent: '#00ff88',
        selection: 'rgba(255, 0, 128, 0.3)',
        black: '#000000',
        red: '#ff0040',
        green: '#00ff88',
        yellow: '#ffff00',
        blue: '#0080ff',
        magenta: '#ff0080',
        cyan: '#00ffff',
        white: '#ffffff',
        brightBlack: '#404040',
        brightRed: '#ff4080',
        brightGreen: '#40ff88',
        brightYellow: '#ffff40',
        brightBlue: '#4080ff',
        brightMagenta: '#ff40c0',
        brightCyan: '#40ffff',
        brightWhite: '#ffffff'
      }
    },
    matrix: {
      name: '黑客帝国',
      theme: {
        foreground: '#00ff00',
        background: '#000000',
        cursor: '#00ff00',
        cursorAccent: '#00ff00',
        selection: 'rgba(0, 255, 0, 0.3)',
        black: '#000000',
        red: '#ff0000',
        green: '#00ff00',
        yellow: '#ffff00',
        blue: '#0000ff',
        magenta: '#ff00ff',
        cyan: '#00ffff',
        white: '#ffffff',
        brightBlack: '#404040',
        brightRed: '#ff4040',
        brightGreen: '#40ff40',
        brightYellow: '#ffff40',
        brightBlue: '#4040ff',
        brightMagenta: '#ff40ff',
        brightCyan: '#40ffff',
        brightWhite: '#ffffff'
      }
    },
    ocean: {
      name: '深海蓝',
      theme: {
        foreground: '#83a598',
        background: '#002b36',
        cursor: '#268bd2',
        cursorAccent: '#83a598',
        selection: 'rgba(38, 139, 210, 0.3)',
        black: '#073642',
        red: '#dc322f',
        green: '#859900',
        yellow: '#b58900',
        blue: '#268bd2',
        magenta: '#d33682',
        cyan: '#2aa198',
        white: '#eee8d5',
        brightBlack: '#586e75',
        brightRed: '#cb4b16',
        brightGreen: '#586e75',
        brightYellow: '#657b83',
        brightBlue: '#839496',
        brightMagenta: '#6c71c4',
        brightCyan: '#93a1a1',
        brightWhite: '#fdf6e3'
      }
    },
    synthwave: {
      name: '合成波',
      theme: {
        foreground: '#f8f8f2',
        background: '#2e1b2e',
        cursor: '#ff6ac1',
        cursorAccent: '#f8f8f2',
        selection: 'rgba(255, 106, 193, 0.3)',
        black: '#000000',
        red: '#ff5c57',
        green: '#5af78e',
        yellow: '#f3f99d',
        blue: '#57c7ff',
        magenta: '#ff6ac1',
        cyan: '#9aedfe',
        white: '#f1f1f0',
        brightBlack: '#686868',
        brightRed: '#ff5c57',
        brightGreen: '#5af78e',
        brightYellow: '#f3f99d',
        brightBlue: '#57c7ff',
        brightMagenta: '#ff6ac1',
        brightCyan: '#9aedfe',
        brightWhite: '#f1f1f0'
      }
    }
  },
  currentTheme: 'cyberpunk'
})

// 基础函数保持不变...
const getList = () => {
  getListHandler(data.clusterId, data.namespace).then(
    (res) => {
      data.items = res.data.data.items
      console.log("items:",data.items)
    }
  )
}

const rollback = (clusterId, namespace)=> {
  data.clusterId = clusterId
  data.namespace = namespace
  getList()
}

const search = ref('')
const filterTableData = computed(() => {
  if (!data.items) return []
  return data.items.filter(item => 
    !search.value ||
    item.metadata?.name?.toLowerCase().includes(search.value.toLowerCase())
  )
})

const deleteItem = (row, force) => {
  console.log("删除:", row)
  ElMessageBox.confirm(
    `你确定要删除命名空间: ${data.namespace} Pod: ${row.metadata.name}吗？`,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteHandler(data.clusterId, data.namespace, row.metadata.name, force).then(
        (res) => {
          ElMessage({
              message: res.data.message,
              type: 'warning',
          })
          getList()
        }
      )
    })
    .catch(() => {
      return
    })
}

const getPodRestartCount = computed(() => (row) => {
  const containerStatuses = row?.status?.containerStatuses;
  if (!containerStatuses) return [0, "0/0"];
  let restartCount = 0
  let readyCount = 0
  row.status.containerStatuses.forEach(item => {
    restartCount += item.restartCount
    if (item.ready){
      readyCount += 1
    }
  })
  const containerTotal = row.status.containerStatuses.length
  const readyStatus = `${readyCount}/${containerTotal}`
  return [restartCount, readyStatus]
})

const showDetail = ref(false)
const detail = (row) => {
  const item = JSON.parse(JSON.stringify(row))
  delete item.metadata.managedFields
  const itemtemp = {
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": item.metadata,
    "spec": item.spec
  }
  const yamlData = obj2Yaml(itemtemp)
  data.yamlContent = yamlData
  showDetail.value = true
}

const handleSelectionChange = (selection)=>{
  console.log("多选:", selection)
  data.options.selectionList = selection
}

const selectionSubmit = ()=>{
  if (data.options.selectionList.length < 2 || data.options.selectionSelected == ""){
    ElMessage.warning("批量操作的数据不能小于两个,且操作不能为空")
    return
  }
  let msg = ""
  if (data.options.selectionSelected == "Delete"){
    msg = "你确定要批量删除多个Pod吗？"
  }else if (data.options.selectionSelected == "ForceDelete"){
    msg = "你确定要批量强制删除多个Pod吗？"
  }
  
  ElMessageBox.confirm(
    msg,
    '',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      data.deleteList = []
      data.options.selectionList.forEach((item) => {
        data.deleteList.push(item.metadata.name)
      })
      deletePodListHandler(data.clusterId,
      data.namespace,
      data.deleteList,
      data.options.selectionSelected=="ForceDelete").then(
        (res)=>{
          ElMessage.success(res.data.message)
          getList()
      })
    })
      .catch(() => {
        return
      })
}

// 🔥 增强的终端相关变量
let drawer = ref(false)
let currentPod = ref()
let currentContainer = ref()
let currentOption = ref()
let curWs = null
let logContent = ref([])
let fitAddon = null
let defaultCommand = ref("/bin/bash")
let term = null
let isTerminalReady = ref(false)

onMounted(() => { 
  console.log("🚀 组件已挂载，Terminal将按需创建")
})

// 🎨 主题切换函数
const changeTheme = (themeName) => {
  data.currentTheme = themeName
  if (term) {
    const selectedTheme = data.terminalThemes[themeName]
    if (selectedTheme) {
      // 更新终端主题
      term.options.theme = selectedTheme.theme
      // 刷新终端显示
      term.refresh(0, term.rows - 1)
      console.log(`🎨 主题已切换到: ${selectedTheme.name}`)
    }
  }
}

const closeWS = (ws) => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    console.log("🔴 关闭WebSocket连接")
    ws.close();
  }
}

const attachTerm = (ws)=>{
  if (!term || !ws) {
    console.error("❌ Terminal或WebSocket不存在，无法绑定")
    return
  }
  
  console.log("🔗 绑定Terminal和WebSocket")
  var attachAddon = new AttachAddon(ws);
  
  const oldSend = attachAddon._sendData;
  attachAddon._sendData = (data)=>{
    const wsMessage = JSON.stringify({
      msgType:"input",
      data:data
    })
    return oldSend.call(attachAddon, wsMessage)
  }
  
  term.loadAddon(attachAddon);
}

const createWS = () => {
  console.log("🚀 创建WebSocket连接")
  let websockerUrl = ""
  logContent.value = []
  
  let origin = ""
  if (import.meta.env.MODE == "sit"){
    origin = "ws://127.0.0.1:8080"
  }else{
    let temp = window.location.origin
    origin = temp.replaceAll("http","ws")
  }
  
  if (currentOption.value == "log"){
    websockerUrl = `${origin}/api/pod/logs?clusterId=${data.clusterId}&namespace=${data.namespace}&name=${currentPod.value.metadata.name}&container=${currentContainer.value}`
  }else if (currentOption.value == "exec"){
    websockerUrl = `${origin}/api/pod/exec?clusterId=${data.clusterId}&namespace=${data.namespace}&name=${currentPod.value.metadata.name}&container=${currentContainer.value}&defaultCommand=${defaultCommand.value}`
  }
  
  let newWs = new WebSocket(websockerUrl);
  
  newWs.onopen = function () {
    console.log("✅ WebSocket连接建立成功")
    // 🎊 连接成功时发送欢迎信息
    if (currentOption.value == "exec" && term) {
      setTimeout(() => {
        term.write('\r\n\x1b[1;32m🚀 终端连接成功！欢迎使用增强型终端\x1b[0m\r\n')
      }, 500)
    }
  }
  
  newWs.onmessage = function(msgContent) {
    if (currentOption.value == "log"){
      logContent.value.push(msgContent.data)
      console.log("logContent:", logContent.value)
    } else if (currentOption.value == "exec"){
      console.log("收到消息: ", msgContent.data);
      
      if (defaultCommand.value == "/bin/bash" && msgContent.data.includes("/bin/bash:no such file or directory")){
        defaultCommand.value = "/bin/sh"
        const oldWs = curWs
        closeWS(oldWs)
        setTimeout(() => {
          let newWs = createWS()
          attachTerm(newWs)
          curWs = newWs
        }, 1000)
      }
    }
  }
  
  newWs.onerror = function() {
    console.error("❌ WebSocket连接错误");
    ElMessage.error("无法建立websocket连接")
  };
  
  newWs.onclose = function() {
    console.log("🔴 WebSocket连接关闭");
    if (currentOption.value == "exec" && term) {
      term.write('\r\n\x1b[1;31m🔌 WebSocket连接已断开\x1b[0m\r\n')
    }
  };
  
  return newWs
}

const cleanupTerminal = () => {
  console.log("🧹 开始清理Terminal资源")
  
  window.removeEventListener('resize', resizeTerm);
  console.log("✅ 已移除resize事件监听器")
  
  if (term) {
    try {
      console.log("🗑️ 销毁Terminal对象")
      term.dispose()
    } catch (e) {
      console.warn("⚠️ Terminal销毁时出错:", e)
    }
    term = null
  }
  
  if (fitAddon) {
    fitAddon = null
  }
  
  isTerminalReady.value = false
  console.log("✅ Terminal资源清理完成")
}

// 🎨 增强的终端创建函数
const createTerminal = () => {
  console.log("🆕 创建新的Terminal")
  
  try {
    if (term) {
      console.log("⚠️ 发现现有Terminal，先清理")
      cleanupTerminal()
    }
    
    // 获取当前主题配置
    const currentThemeConfig = data.terminalThemes[data.currentTheme]
    const termConfig = {
      ...data.termOptions,
      theme: currentThemeConfig.theme
    }
    
    term = new Terminal(termConfig);
    fitAddon = new FitAddon();
    term.loadAddon(fitAddon);
    
    // 🎉 添加终端启动动画
    term.onData((data) => {
      // 可以在这里添加特殊效果
    });
    
    console.log("✅ Terminal对象创建成功")
    return true
    
  } catch (error) {
    console.error("❌ Terminal创建失败:", error)
    return false
  }
}

const beforeDrawerClose = () => {
  console.log("🚪 准备关闭Drawer")
  
  if (curWs) {
    closeWS(curWs)
    curWs = null
  }
  
  if (currentOption.value == "exec"){
    cleanupTerminal()
  }
  
  drawer.value = false
  console.log("✅ Drawer已关闭，资源已清理")
}

const logExec = (row, arg) => {
  console.log("🚀 启动", arg, ":", row.metadata.name)
  
  currentOption.value = arg
  currentPod.value = row
  currentContainer.value = row.spec.containers[0].name
  
  const newWs = createWS()
  curWs = newWs
  
  drawer.value = true
}

const containerChanged = () => {
  console.log("🔄 更换容器:", currentContainer.value)
  
  if (curWs) {
    closeWS(curWs)
    curWs = null
  }
  
  setTimeout(() => {
    const newWs = createWS()
    if (term && currentOption.value === "exec") {
      attachTerm(newWs)
    }
    curWs = newWs
  }, 500)
}

const resizeTerm = () => {
  if (drawer.value == false || !term || !fitAddon){
    return
  }
  
  try {
    fitAddon.fit()
    const dims = fitAddon.proposeDimensions()
    
    if (dims && curWs && curWs.readyState === WebSocket.OPEN) {
      const msg = JSON.stringify({
        msgType: "resize",
        cols: dims.cols,
        rows: dims.rows
      })
      curWs.send(msg)
      console.log("📏 发送大小调整:", msg)
    }
  } catch (error) {
    console.error("❌ 调整terminal大小失败:", error);
  }
}

// 🎨 全新的openDrawer函数 - 添加启动动画
const openDrawer = () => {
  console.log("🚪 打开Drawer，模式:", currentOption.value)
  if (currentOption.value == 'exec'){
    nextTick(() => {
      console.log("⏱️ DOM已渲染，开始初始化Terminal")
      
      const success = createTerminal()
      if (!success) {
        console.error("❌ Terminal创建失败")
        ElMessage.error("Terminal初始化失败")
        return
      }
      
      const terminalElement = document.getElementById('terminal');
      if (!terminalElement) {
        console.error("❌ 找不到terminal DOM元素")
        ElMessage.error("找不到terminal容器")
        return
      }
      
      try {
        console.log("🖥️ 将Terminal绑定到DOM")
        term.open(terminalElement);
        
        // 调整大小
        resizeTerm()
        
        // 🎊 启动动画 - 从第一行开始，真正居中
        term.write('\x1b[2J\x1b[3J\x1b[H') // 清屏并回到第一行
        
        // 获取实际终端尺寸
        const actualCols = term.cols || 120
        console.log('实际终端宽度:', actualCols)
        
        // 计算真正居中的框框
        term.write('\x1b[1;36m')
        const frameWidth = 46  // 调整框框宽度
        const padding = Math.floor((actualCols - frameWidth) / 2)
        const paddingStr = ' '.repeat(Math.max(0, padding))
        
        console.log('框框宽度:', frameWidth, '填充空格:', padding, '终端宽度:', actualCols)
        
        // 从第一行开始显示真正居中的框框
        term.write(paddingStr + '╔' + '═'.repeat(frameWidth - 2) + '╗\r\n')
        term.write(paddingStr + '║' + ' '.repeat(13) + '🚀 增强型终端启动中...' + ' '.repeat(10) + '║\r\n')
        term.write(paddingStr + '╚' + '═'.repeat(frameWidth - 2) + '╝\r\n')
        term.write('\x1b[0m')
        
        // 添加空行，为后续内容留出空间
        term.write('\r\n\r\n')
        
        // 调整大小
        resizeTerm()
        
        window.addEventListener('resize', resizeTerm);
        term.focus();
        
        isTerminalReady.value = true
        console.log("✅ Terminal已成功绑定到DOM")
        
        if (curWs && curWs.readyState === WebSocket.OPEN) {
          console.log("🔗 WebSocket已准备好，立即绑定")
          attachTerm(curWs)
        } else {
          console.log("⏳ 等待WebSocket连接...")
          const checkWs = setInterval(() => {
            if (curWs && curWs.readyState === WebSocket.OPEN) {
              console.log("🔗 WebSocket现在准备好了，绑定Terminal")
              attachTerm(curWs)
              clearInterval(checkWs)
            }
          }, 100)
          
          setTimeout(() => {
            clearInterval(checkWs)
          }, 10000)
        }
        
      } catch (error) {
        console.error("❌ Terminal绑定DOM失败:", error)
        ElMessage.error("Terminal绑定失败")
      }
    })
  }
}

const {yamlContent,options} = toRefs(data)
</script>

<template>
  <List title="Pod列表">
    <template #header-options>
      <ClusterNamespaceSelector @namespaceChangedRollback="rollback">
      </ClusterNamespaceSelector>
      <el-input v-model="search" size="small" placeholder="搜索" style="width: 140px; margin-left: 10px; height: 32px;" />
    </template>
    <template #main>
      <el-table
      border 
      height="480" 
      :data="filterTableData" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :default-sort="{prop: 'metadata.creationTimestamp', order: 'descending'}"
      >
      <el-table-column type="selection" width="55"/>
        <el-table-column fixed prop="" align="center" label="名称" width="320">
          <template #default="scope">
            <el-button link type="primary"  @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="metadata.creationTimestamp" align="center" label="创建时间" width="240" sortable />
        <el-table-column prop="metadata.namespace" align="center" label="命名空间" width="240" />
        <el-table-column prop="" align="center" label="状态" width="120" sortable>
          <template #default="scope">
            <span v-if="scope.row.status.phase == 'Running'" style="color: green;">Running</span>
            <span v-else  style="color: red;">{{ scope.row.status.phase }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="重启次数" width="120">
          <template #default="scope">
            <span v-if="!scope.row.metadata.deletionTimestamp">{{ getPodRestartCount(scope.row)[0] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="容器状态" width="120">
          <template #default="scope">
            <span v-if="!scope.row.metadata.deletionTimestamp">{{ getPodRestartCount(scope.row)[1] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status.podIP" align="center" label="Pod IP" width="240" />
        <el-table-column prop="spec.nodeName" align="center" label="宿主机主机名" width="240" />
        <el-table-column prop="status.hostIP" align="center" label="宿主机IP" width="240" />
        <el-table-column fixed="right" align="center" label="操作" width="320" >
          <template #default="scope">
            <el-button v-if="!scope.row.metadata.deletionTimestamp" link type="warning" @click="deleteItem(scope.row, false)">删除</el-button>
            <el-button v-else link type="warning" @click="deleteItem(scope.row, true)">强制删除</el-button>
            <el-button link v-if="!scope.row.metadata.deletionTimestamp" @click="logExec(scope.row,'exec')" type="primary">执行命令</el-button>
            <el-button link v-if="!scope.row.metadata.deletionTimestamp" @click="logExec(scope.row,'log')" type="primary">查看日志</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #footer-left>
      <div style="display: flex; align-items: center; ">
        <el-select v-model="options.selectionSelected" placeholder="请选择批量的操作" style="width: 180px; ">
          <el-option v-for="item in options.selectionOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
          </el-option>
        </el-select>
        <el-button style="margin-left: 10px;" type="warning" @click="selectionSubmit()">确定</el-button>
      </div>
    </template>
    <template #footer-right>
      <span>总数：{{ filterTableData.length }}</span>
    </template>
  </List>
  
  <el-dialog v-model="showDetail" width="70%">
  <template #header="{ titleId, titleClass }">
    <div class="my-header">
      <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
        <el-button type="primary" title="资源所在的集群" >
          <i class="iconfont icon-kubernetes" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.clusterId }}</span>
        </el-button>
        <el-button type="primary" title="资源所在的命名空间" >
          <i class="iconfont icon-Namespace" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.namespace }}</span>
        </el-button>
      </div>
    </div>
  </template>
    <CodeMirror v-model="yamlContent"></CodeMirror>
  </el-dialog>
  
  <!-- 🚀 全新炫酷终端界面 -->
   <el-drawer 
   v-model="drawer"
   direction="btt" 
   :before-close="beforeDrawerClose"
   :with-header="false"
   @opened="openDrawer"
   size="65%"
   class="terminal-drawer">
   
   <!-- 🎨 全新设计的头部区域 -->
   <div class="terminal-header">
     <!-- 左侧：Pod信息 -->
     <div class="header-left">
       <div class="pod-info-card">
         <div class="pod-icon-wrapper">
           <el-icon :size="32" class="pod-icon">
             <i class="iconfont icon-POD"></i>
           </el-icon>
           <div class="status-indicator" :class="{ active: isTerminalReady }"></div>
         </div>
         <div class="pod-details">
           <h3 class="pod-name">{{ currentPod?.metadata?.name }}</h3>
           <div class="pod-meta">
             <span class="pod-status">{{ currentOption === 'exec' ? '🔧 执行终端' : '📋 日志查看' }}</span>
             <span class="cluster-info">{{ data.clusterId }}/{{ data.namespace }}</span>
           </div>
         </div>
       </div>
     </div>
     
     <!-- 中间：控制区域 -->
     <div class="header-center">
       <!-- 🔄 容器选择器 -->
       <div class="container-selector-wrapper" v-if="currentPod?.spec?.containers?.length > 1">
         <label class="selector-label">容器:</label>
         <el-select 
           v-model="currentContainer" 
           @change="containerChanged"
           size="small"
           class="container-select">
           <el-option 
             v-for="c in currentPod?.spec?.containers" 
             :key="c.name"
             :label="c.name" 
             :value="c.name">
             <span class="container-option">
               <i class="container-icon">📦</i>
               {{ c.name }}
             </span>
           </el-option>
         </el-select>
       </div>
       
       <!-- 单容器显示 -->
       <div class="single-container" v-else>
         <span class="container-badge">
           <i class="container-icon">📦</i>
           {{ currentContainer }}
         </span>
       </div>
     </div>
     
     <!-- 右侧：工具区域 -->
     <div class="header-right">
       <!-- 🎭 主题选择器 -->
       <div class="theme-selector" v-if="currentOption === 'exec'">
         <label class="selector-label">主题:</label>
         <el-select 
           v-model="data.currentTheme" 
           @change="changeTheme"
           size="small"
           class="theme-select">
           <el-option 
             v-for="(theme, key) in data.terminalThemes" 
             :key="key"
             :label="theme.name" 
             :value="key">
             <span class="theme-option">
               <span class="theme-preview" :style="{ backgroundColor: theme.theme.background, color: theme.theme.foreground }">●</span>
               {{ theme.name }}
             </span>
           </el-option>
         </el-select>
       </div>
       
       <!-- 连接状态 -->
       <div class="connection-status-wrapper">
         <div class="connection-status" :class="{ connected: isTerminalReady }">
           <span class="status-dot"></span>
           <span class="status-text">{{ isTerminalReady ? '已连接' : '连接中' }}</span>
         </div>
       </div>
       
       <!-- 关闭按钮 -->
       <button class="close-btn" @click="beforeDrawerClose" title="关闭终端">
         <i class="close-icon">✕</i>
       </button>
     </div>
   </div>
   
   <!-- 🖥️ 内容区域 -->
   <div class="terminal-content">
     <template v-if="currentOption == 'log'">
        <div class="log-container">
          <el-table :data="logContent" style="width: 100%;" class="log-table">
            <el-table-column>
              <template #default="scope">
                <pre class="log-line">{{ scope.row }}</pre>
              </template>
            </el-table-column>
          </el-table>
        </div>
     </template>
     <template v-else-if="currentOption == 'exec'">
       <!-- 🎮 终端控制栏 -->
       <div class="terminal-controls">
         <div class="control-buttons">
           <button class="control-btn close" @click="beforeDrawerClose"></button>
           <button class="control-btn minimize"></button>
           <button class="control-btn maximize"></button>
         </div>
         <div class="terminal-title">
           <span class="title-text">🚀 增强型终端 v2.0</span>
           <span class="connection-status" :class="{ connected: isTerminalReady }">
             {{ isTerminalReady ? '🟢 已连接' : '🔴 连接中...' }}
           </span>
         </div>
       </div>
       
       <!-- 🖥️ 终端主体 -->
       <div class="terminal-wrapper">
         <div id="terminal" class="terminal-main"></div>
         <!-- 🌟 扫描线特效 -->
         <div class="scanline"></div>
         <!-- ✨ 闪烁效果 -->
         <div class="terminal-glow"></div>
       </div>
     </template>
   </div>
</el-drawer>
</template>

<style scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

/* 🎨 终端相关样式 */
.terminal-drawer {
  background: linear-gradient(135deg, #0a0a0a 0%, #1a0a1a 100%);
}

.terminal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(26, 10, 26, 0.95) 100%);
  border-bottom: 1px solid rgba(0, 255, 136, 0.2);
  backdrop-filter: blur(20px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.header-left, .header-center, .header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-center {
  flex: 1;
  justify-content: center;
}

.pod-info-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  background: rgba(0, 255, 136, 0.05);
  border: 1px solid rgba(0, 255, 136, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.pod-icon-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pod-icon {
  color: #00ff88;
  filter: drop-shadow(0 0 8px rgba(0, 255, 136, 0.4));
  font-size: 28px !important;
}

.status-indicator {
  position: absolute;
  top: -2px;
  right: -2px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff0080;
  box-shadow: 0 0 8px rgba(255, 0, 128, 0.6);
  animation: pulse 2s infinite;
}

.status-indicator.active {
  background: #00ff88;
  box-shadow: 0 0 8px rgba(0, 255, 136, 0.6);
}

@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.7; transform: scale(1.2); }
}

.pod-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.pod-name {
  margin: 0;
  color: #00ff88;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 0 8px rgba(0, 255, 136, 0.3);
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pod-meta {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.pod-status {
  color: #ff0080;
  font-size: 11px;
  font-weight: 500;
  opacity: 0.9;
}

.cluster-info {
  color: rgba(255, 255, 255, 0.6);
  font-size: 10px;
  font-family: monospace;
}

.container-selector-wrapper, .theme-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.selector-label {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

.container-select, .theme-select {
  min-width: 120px;
}

.single-container {
  display: flex;
  align-items: center;
}

.container-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: rgba(0, 128, 255, 0.1);
  border: 1px solid rgba(0, 128, 255, 0.3);
  border-radius: 8px;
  color: #0080ff;
  font-size: 12px;
  font-weight: 500;
}

.container-icon {
  font-size: 14px;
}

.container-option, .theme-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.theme-preview {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
}

.connection-status-wrapper {
  display: flex;
  align-items: center;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #ff0080;
  animation: blink 1.5s infinite;
}

.connection-status.connected .status-dot {
  background: #00ff88;
  animation: none;
}

.status-text {
  color: #ff0080;
}

.connection-status.connected .status-text {
  color: #00ff88;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.3; }
}

.close-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 8px;
  background: rgba(255, 0, 128, 0.1);
  border: 1px solid rgba(255, 0, 128, 0.3);
  color: #ff0080;
  cursor: pointer;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 0, 128, 0.2);
  border-color: rgba(255, 0, 128, 0.5);
  transform: scale(1.05);
}

.close-icon {
  font-size: 14px;
  font-weight: bold;
}

.terminal-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100% - 80px);
}

.log-container {
  flex: 1;
  background: #000;
  color: #00ff88;
  font-family: 'Fira Code', monospace;
}

.log-table {
  background: #000 !important;
}

.log-line {
  color: #00ff88;
  font-family: 'Fira Code', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  margin: 0;
}

.terminal-controls {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 15px;
  background: linear-gradient(90deg, #1a1a1a 0%, #2a1a2a 100%);
  border-bottom: 1px solid rgba(0, 255, 136, 0.2);
}

.control-buttons {
  display: flex;
  gap: 8px;
}

.control-btn {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.control-btn.close {
  background: #ff5f56;
  box-shadow: 0 0 10px rgba(255, 95, 86, 0.3);
}

.control-btn.minimize {
  background: #ffbd2e;
  box-shadow: 0 0 10px rgba(255, 189, 46, 0.3);
}

.control-btn.maximize {
  background: #27ca3f;
  box-shadow: 0 0 10px rgba(39, 202, 63, 0.3);
}

.control-btn:hover {
  transform: scale(1.2);
  filter: brightness(1.2);
}

.terminal-title {
  display: flex;
  align-items: center;
  gap: 15px;
}

.title-text {
  color: #00ff88;
  font-weight: bold;
  font-size: 14px;
  text-shadow: 0 0 5px rgba(0, 255, 136, 0.3);
}

.terminal-wrapper {
  flex: 1;
  position: relative;
  background: #0a0a0a;
  border: 2px solid rgba(0, 255, 136, 0.3);
  border-radius: 8px;
  margin: 10px;
  overflow: hidden;
  box-shadow: 
    0 0 20px rgba(0, 255, 136, 0.2),
    inset 0 0 20px rgba(0, 0, 0, 0.5);
}

.terminal-main {
  width: 100%;
  height: 100%;
  padding: 10px;
  position: relative;
  z-index: 2;
  text-align: left;
}

/* 🌟 扫描线特效 */
.scanline {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, #00ff88, transparent);
  animation: scanline 2s linear infinite;
  z-index: 3;
  opacity: 0.3;
}

@keyframes scanline {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(400px);
  }
}

/* ✨ 终端发光效果 */
.terminal-glow {
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(45deg, #00ff88, #ff0080, #0080ff, #00ff88);
  background-size: 400% 400%;
  animation: glow-border 4s ease-in-out infinite;
  z-index: 1;
  border-radius: 8px;
  opacity: 0.1;
}

@keyframes glow-border {
  0%, 100% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
}

/* 🎨 自定义滚动条 */
.terminal-wrapper ::-webkit-scrollbar {
  width: 8px;
}

.terminal-wrapper ::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.3);
}

.terminal-wrapper ::-webkit-scrollbar-thumb {
  background: linear-gradient(45deg, #00ff88, #ff0080);
  border-radius: 4px;
}

.terminal-wrapper ::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(45deg, #40ff88, #ff40c0);
}

/* 🎭 选择器样式增强 */
:deep(.el-select .el-input__wrapper) {
  background: rgba(0, 0, 0, 0.6) !important;
  border: 1px solid rgba(0, 255, 136, 0.3) !important;
  border-radius: 8px !important;
  backdrop-filter: blur(10px);
}

:deep(.el-select .el-input__inner) {
  color: #00ff88 !important;
  font-size: 12px !important;
}

:deep(.el-select-dropdown) {
  background: rgba(0, 0, 0, 0.95) !important;
  border: 1px solid rgba(0, 255, 136, 0.3) !important;
  border-radius: 8px !important;
  backdrop-filter: blur(20px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
}

:deep(.el-select-dropdown__item) {
  color: #00ff88 !important;
  font-size: 12px !important;
  padding: 8px 12px !important;
}

:deep(.el-select-dropdown__item:hover) {
  background: rgba(0, 255, 136, 0.15) !important;
}

:deep(.el-select-dropdown__item.selected) {
  background: rgba(0, 255, 136, 0.2) !important;
  color: #fff !important;
}

/* 📱 响应式设计 */
@media (max-width: 768px) {
  .terminal-header {
    flex-direction: column;
    gap: 12px;
    padding: 12px 16px;
  }
  
  .header-left, .header-center, .header-right {
    width: 100%;
    justify-content: center;
  }
  
  .header-center {
    order: 2;
  }
  
  .header-right {
    order: 3;
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .pod-info-card {
    width: 100%;
    justify-content: center;
  }
  
  .pod-name {
    max-width: none;
    text-align: center;
  }
  
  .container-select, .theme-select {
    min-width: 100px;
  }
  
  .selector-label {
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .terminal-header {
    padding: 8px 12px;
    gap: 8px;
  }
  
  .pod-info-card {
    padding: 6px 12px;
  }
  
  .pod-icon {
    font-size: 24px !important;
  }
  
  .pod-name {
    font-size: 14px;
  }
  
  .theme-selector, .container-selector-wrapper {
    flex-direction: column;
    gap: 4px;
    align-items: center;
  }
}

/* 🎨 动画和过渡效果 */
.terminal-drawer {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.terminal-main {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 🔥 特殊效果 - 光标呼吸效果 */
.terminal-main :deep(.xterm-cursor) {
  animation: cursorBreathe 1.5s ease-in-out infinite;
}

@keyframes cursorBreathe {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
}

/* 🔧 确保终端内容左对齐 */
.terminal-main :deep(.xterm-screen) {
  text-align: left !important;
}

.terminal-main :deep(.xterm-viewport) {
  text-align: left !important;
}

.terminal-main :deep(.xterm-rows) {
  text-align: left !important;
}

.terminal-main :deep(.xterm-row) {
  text-align: left !important;
  justify-content: flex-start !important;
}
</style>
